package com.hudongwx.godoffood.activity.home_activity;

import android.content.Intent;
import android.graphics.Rect;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.hudongwx.godoffood.R;
import com.hudongwx.godoffood.fragment.HomeFragment;
import com.hudongwx.godoffood.utils.API.API;
import com.hudongwx.godoffood.utils.MyJsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

//import cn.sharesdk.framework.ShareSDK;
//import cn.sharesdk.onekeyshare.OnekeyShare;

@ContentView(R.layout.activity_subject)
public class SubjectActivity extends AppCompatActivity {
    private String TAG="SubjectActivity";
    @ViewInject(R.id.subject_title)
    TextView title;
    @ViewInject(R.id.subject_time)
    TextView time;
    @ViewInject(R.id.subject_zan_num)
    TextView zanNum;
    @ViewInject(R.id.subject_web)
    WebView webView;

    @ViewInject(R.id.subject_title_img)
    ImageView img;
    @ViewInject(R.id.subject_about_goods)
    RecyclerView recyclerView;
    private String id = null;

//    private String url=null;
    private String shareTitle,shareContent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        //获取页面对应id
        id = getIntent().getStringExtra("Id");
        webView.getSettings().setJavaScriptEnabled(true);
        //设置是否作为默认浏览器打开
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return true;
            }
        });
        loadSubjectContent(id);
    }

    /**
     * 加载专题内容
     * @param id
     */
    public void loadSubjectContent(String id){
        RequestParams params = new RequestParams(API.getSubject(id));
        x.http().get(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {
                try {
                    JSONObject data = result.getJSONObject("Data");

                    title.setText(data.getString("Title"));
                    time.setText(data.getString("Datetime"));
                    zanNum.setText(data.getInt("SupportCount")+"");
                    //分享标题
                    shareTitle = data.getString("Title");
                    //f分享内容
                    shareContent = data.getString("ShortDesc");
                    x.image().bind(img,data.getString("CoverUrl"));
                    //网页加载设置
                    String loadData = data.getString("Content");
                    String webHTML = "<html><head><style>img{height=auto;}</style></head><body>"+loadData+"</body></html>";
                    webView.loadDataWithBaseURL(null,webHTML,"text/html","utf-8",null);

                    GridLayoutManager manager = new GridLayoutManager(SubjectActivity.this,3);
                    recyclerView.setLayoutManager(manager);
                    //设置recyclerview的item之间的间距
                    recyclerView.addItemDecoration(new SpaceItemDecoration(20));
                    recyclerView.setAdapter(new RecyclerAdapter(data.getJSONArray("ProductList")));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    class RecyclerAdapter extends RecyclerView.Adapter<AboutViewHolder>{
        JSONArray data;

        public RecyclerAdapter(JSONArray data) {
            this.data = data;
            Log.i(TAG, "RecyclerAdapter: ");
        }

        @Override
        public AboutViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(SubjectActivity.this).inflate(R.layout.about_goods_item, null);
            return new AboutViewHolder(view);
        }

        @Override
        public void onBindViewHolder(AboutViewHolder holder, int position) {
            try {
                JSONObject item = data.getJSONObject(position);
                x.image().bind(holder.imageView,item.getString("Img"));
                holder.textView.setText(item.getString("ProductName"));

                ItemClickListener listener = new ItemClickListener();
                String[] productIDList = new String[2];//用于存放商品ID
                String productId1 = item.getString("ProductId");
                String productId2 = productId1.replaceAll("_D","");
                productIDList[0] = productId1;
                productIDList[1] = productId2;
                holder.imageView.setTag(productIDList);
                holder.imageView.setOnClickListener(listener);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public int getItemCount() {
            return data.length();
        }
    }

    class AboutViewHolder extends RecyclerView.ViewHolder{
        private ImageView imageView;
        private TextView textView;

        public AboutViewHolder(View itemView) {
            super(itemView);
            this.imageView = (ImageView) itemView.findViewById(R.id.item_img);
            this.textView = (TextView) itemView.findViewById(R.id.item_tv);
        }
    }


    class ItemClickListener implements View.OnClickListener{

        @Override
        public void onClick(View v) {
            Intent intent = new Intent(SubjectActivity.this, FoodGoodsPageActivity.class);
            intent.putExtra("productID", (String[]) v.getTag());
            startActivity(intent);

        }
    }

    //设置recyclerview的item之间的间距
    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private int space;

        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.left = space;
            outRect.right = space;
            outRect.bottom = space;
            outRect.top = space;
            // Add top margin only for the first item to avoid double space between items
//            if(parent.getChildPosition(view) == 0)
//                outRect.top = space;
        }

    }


    @Event(R.id.subject_zan)
    private void zan(View view){
        int num = Integer.parseInt((zanNum.getText()+""));
        num++;
        zanNum.setText(num+"");
        postZan(id);
    }

    /**
     * 点赞时会发送请求
     * @param id
     */
    public void postZan(String id){
        RequestParams params = new RequestParams(API.getZanUrl());
        params.addBodyParameter("Action","addSupport");
        params.addBodyParameter("id",id);
        x.http().post(params, new Callback.CommonCallback<MyJsonObject>() {
            @Override
            public void onSuccess(MyJsonObject result) {

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    @Event(R.id.subject_share)
    private void showShare(View view) {
//        ShareSDK.initSDK(this);
//        OnekeyShare oks = new OnekeyShare();
//        //关闭sso授权
//        oks.disableSSOWhenAuthorize();
//
//        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
////        oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
//        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
//        oks.setTitle(shareTitle);
//        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
//        oks.setTitleUrl(API.getShareUrl(id));
//        // text是分享文本，所有平台都需要这个字段
//        oks.setText(shareContent);
//        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//        //oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
//        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
//        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
//        // url仅在微信（包括好友和朋友圈）中使用
//        oks.setUrl(API.getShareUrl(id));
//        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
//        // oks.setComment("我是测试评论文本");
//        // site是分享此内容的网站名称，仅在QQ空间使用
//        oks.setSite(shareTitle);
//        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
////        oks.setSiteUrl("http://sharesdk.cn");
//
//// 启动分享GUI
//        oks.show(this);
    }

    @Event(R.id.subject_back)
    private void back(View view){
        super.onBackPressed();
    }
}
